;
(function() {
	var wx_pay = require("./pay");
	var wx_core = require("./core");
	var Fiber = require('fibers');

	function WX(appId, appSecret, mchId, key) {
		this.appId = appId;
		this.appSecret = appSecret;
		this.mchId = mchId;
		this.key = key;
		this.access_token = "";
		this.jsapi_ticket = "";
	};

	function get_access_token() {
		var self = this;
		var access_token_info = curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}".format({
			appId: this.appId,
			appSecret: this.appSecret
		})).parseJSON();
		console.log(access_token_info);

		this.wx_access_token = access_token_info.access_token;
		return this.wx_access_token;
	};

	function get_jsapi_ticket() {
		var self = this;
		var jsapi_ticket_info = curl("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={ACCESS_TOKEN}&type=jsapi".format({
			ACCESS_TOKEN: this.wx_access_token
		})).parseJSON();
		console.log(jsapi_ticket_info);

		if (jsapi_ticket_info.errcode != 0) {
			console.error("WX JS API TICKET ERROR:" + jsapi_ticket_info.errmsg);
			return;
		}
		this.wx_jsapi_ticket = jsapi_ticket_info.ticket;
		return this.wx_jsapi_ticket;
	};

	function get_jsapi_signature(url, noncestr, timestamp) {
		noncestr || (noncestr = Math.random().toString(36).substr(2));
		timestamp = parseInt(timestamp || ((+new Date) / 1000));
		var sign_str = "jsapi_ticket={wx_jsapi_ticket}&noncestr={noncestr}&timestamp={timestamp}&url={url}".format({
			wx_jsapi_ticket: this.wx_jsapi_ticket,
			noncestr: noncestr,
			timestamp: timestamp,
			url: url
		});
		var signature = wx_core.sha1(sign_str);
		console.log("get_jsapi_signature:", sign_str, "\n", signature);
		return {
			nonceStr: noncestr,
			timestamp: timestamp,
			signature: signature
		};
	};

	function get_web_access_token(code) {
		if (!code) {
			throw "GET WEB ACCESS TOKEN ERROR:Code 不可为空";
		}
		var web_access_token = curl("https://api.weixin.qq.com/sns/oauth2/access_token?appid={APPID}&secret={SECRET}&code={CODE}&grant_type=authorization_code".format({
			APPID: this.appId,
			SECRET: this.appSecret,
			CODE: code
		})).parseJSON();
		if (web_access_token.errcode) {
			throw "GET WEB ACCESS TOKEN ERROR:(" + web_access_token.errcode + ")" + web_access_token.errmsg;
		}
		return web_access_token;
	};

	function refresh_web_access_token(web_access_token) {
		// body...
	}
	WX.prototype = {
		core: wx_core,
		pay: wx_pay,
		// js_unified_order: wx_pay.js_unified_order,
		get_access_token: get_access_token,
		get_jsapi_ticket: get_jsapi_ticket,
		get_jsapi_signature: get_jsapi_signature,
		get_web_access_token: get_web_access_token
	}
	module.exports = WX;

}());